#!/bin/bash

# Eclipse Mosquitto 简化版交叉编译脚本 - 只编译客户端库
# 专为嵌入式MQTT客户端使用设计

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MOSQUITTO_VERSION="2.0.18"
MOSQUITTO_DIR="mosquitto-${MOSQUITTO_VERSION}"
MOSQUITTO_ARCHIVE="${MOSQUITTO_DIR}.tar.gz"
DOWNLOAD_URL="https://mosquitto.org/files/source/${MOSQUITTO_ARCHIVE}"

# 交叉编译配置
CROSS_COMPILE="riscv64-anyka-linux-musl-"
TARGET_ARCH="riscv64"
BUILD_DIR="${SCRIPT_DIR}/build_${TARGET_ARCH}"
INSTALL_DIR="${SCRIPT_DIR}/install/${TARGET_ARCH}"

# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查工具链
check_toolchain() {
    log_info "检查RISC-V交叉编译工具链..."
    if ! command -v ${CROSS_COMPILE}gcc >/dev/null 2>&1; then
        log_error "未找到RISC-V交叉编译器: ${CROSS_COMPILE}gcc"
        exit 1
    fi
    log_info "工具链检查通过: $(${CROSS_COMPILE}gcc --version | head -1)"
}

# 下载并解压源码
prepare_source() {
    log_info "准备源码..."
    cd "$SCRIPT_DIR"
    
    # 下载源码包
    if [ ! -f "$MOSQUITTO_ARCHIVE" ]; then
        log_info "下载源码包..."
        if command -v wget >/dev/null 2>&1; then
            wget "$DOWNLOAD_URL"
        elif command -v curl >/dev/null 2>&1; then
            curl -L -O "$DOWNLOAD_URL"
        else
            log_error "需要wget或curl下载源码"
            exit 1
        fi
    fi
    
    # 解压
    [ -d "$MOSQUITTO_DIR" ] && rm -rf "$MOSQUITTO_DIR"
    tar -xzf "$MOSQUITTO_ARCHIVE"
    log_info "源码准备完成"
}

# 编译mosquitto客户端库
build_lib() {
    log_info "编译mosquitto客户端库..."
    
    # 准备目录
    rm -rf "$BUILD_DIR" "$INSTALL_DIR"
    mkdir -p "$BUILD_DIR" "$INSTALL_DIR"/{include,lib}
    
    cd "$SCRIPT_DIR/$MOSQUITTO_DIR/lib"
    
    # 设置编译环境
    export CC="${CROSS_COMPILE}gcc"
    export AR="${CROSS_COMPILE}ar"
    export RANLIB="${CROSS_COMPILE}ranlib"
    
    # 创建简化的config.h
    cat > ../config.h << 'EOF'
#ifndef CONFIG_H
#define CONFIG_H
#define VERSION "2.0.18"
#define WITH_THREADING 1
#define WITH_TLS 0
#define WITH_WEBSOCKETS 0
#define WITH_BROKER 0
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
EOF
    
    # 编译参数
    CFLAGS="-O2 -Wall -fPIC -I.. -DWITH_THREADING -DVERSION=\\\"2.0.18\\\""
    
    # 编译源文件
    log_info "编译源文件..."
    SOURCE_FILES="mosquitto.c"
    OBJECT_FILES=""
    
    for src in $SOURCE_FILES; do
        obj="${src%.c}.o"
        log_info "编译 $src"
        $CC $CFLAGS -c "$src" -o "$obj"
        OBJECT_FILES="$OBJECT_FILES $obj"
    done
    
    # 创建静态库
    log_info "创建静态库..."
    $AR rcs libmosquitto.a $OBJECT_FILES
    $RANLIB libmosquitto.a
    
    # 创建动态库
    log_info "创建动态库..."
    $CC -shared -fPIC $CFLAGS $OBJECT_FILES -o libmosquitto.so.1.6.18
    ln -sf libmosquitto.so.1.6.18 libmosquitto.so.1
    ln -sf libmosquitto.so.1 libmosquitto.so
    
    # 安装文件
    log_info "安装文件..."
    cp libmosquitto.a libmosquitto.so* "$INSTALL_DIR/lib/"
    cp mosquitto.h "$INSTALL_DIR/include/"
    
    log_info "编译完成"
}

# 验证安装
verify_installation() {
    log_info "验证安装..."
    
    local files=(
        "$INSTALL_DIR/include/mosquitto.h"
        "$INSTALL_DIR/lib/libmosquitto.a"
        "$INSTALL_DIR/lib/libmosquitto.so"
    )
    
    for file in "${files[@]}"; do
        if [ -f "$file" ]; then
            log_info "✓ $file"
        else
            log_error "✗ $file 缺失"
            return 1
        fi
    done
    
    # 显示库大小
    local size=$(du -h "$INSTALL_DIR/lib/libmosquitto.a" | cut -f1)
    log_info "静态库大小: $size"
    
    # 创建pkg-config文件
    mkdir -p "$INSTALL_DIR/lib/pkgconfig"
    cat > "$INSTALL_DIR/lib/pkgconfig/libmosquitto.pc" << EOF
prefix=$INSTALL_DIR
exec_prefix=\${prefix}
libdir=\${exec_prefix}/lib
includedir=\${prefix}/include

Name: libmosquitto
Description: Eclipse Mosquitto MQTT client library
Version: $MOSQUITTO_VERSION
Libs: -L\${libdir} -lmosquitto
Cflags: -I\${includedir}
EOF
    
    log_info "安装验证通过"
}

# 清理
cleanup() {
    log_info "清理临时文件..."
    cd "$SCRIPT_DIR"
    rm -rf "$MOSQUITTO_DIR"
}

# 主函数
main() {
    log_info "开始构建Mosquitto客户端库 (RISC-V)"
    log_info "版本: $MOSQUITTO_VERSION"
    log_info "安装目录: $INSTALL_DIR"
    
    check_toolchain
    prepare_source
    build_lib
    verify_installation
    cleanup
    
    log_info "构建成功！"
    log_info ""
    log_info "使用方法:"
    log_info "  头文件: $INSTALL_DIR/include/mosquitto.h"
    log_info "  静态库: $INSTALL_DIR/lib/libmosquitto.a"
    log_info "  动态库: $INSTALL_DIR/lib/libmosquitto.so"
    log_info ""
    log_info "编译命令:"
    log_info "  ${CROSS_COMPILE}gcc -I$INSTALL_DIR/include your_code.c -L$INSTALL_DIR/lib -lmosquitto"
}

main "$@"